package com.qinghe.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;

/**
 * Bean属性转换工具类
 * 
 * @author longfei
 */
public abstract class BeanUtils extends org.springframework.beans.BeanUtils {
    private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

	/**
     * 把Bean数据转换到另外一个类的对象中。
     * 
     * @param source 数据源
     * @param targetClass 目标对象的类
     * @return 目标对象
     */
    public static Object convert(Object source, Class<?> targetClass) {
    	if (source == null) {
            return null;
        }
        try {
            Object target = targetClass.newInstance();
            copyProperties(source, target);
            return target;
        } catch (InstantiationException e) {
            logger.error("Can't create Instance of Class:" + targetClass, e);
        } catch (IllegalAccessException e) {
            logger.error("Can't access construct method of Class:" + targetClass, e);
        }
        return null;
    }

	/**
     * 把Bean集合数据转换到另外一个类的集合对象中。
     * 
     * @param sources 数据源集合
     * @param targetClass 目标对象的类
     * @return 目标对象
     */
    public static Object convert(Collection<?> sources, Class<?> targetClass) {
    	if (sources == null) {
            return null;
        }
        try {
        	List<Object> targets = new ArrayList<Object>();
            Object target = null;
            for (Object obj : sources) {
            	target = targetClass.newInstance();
                copyProperties(obj, target);
                targets.add(target);
            }
            return targets;
        } catch (InstantiationException e) {
            logger.error("Can't create Instance of Class:" + targetClass, e);
        } catch (IllegalAccessException e) {
            logger.error("Can't access construct method of Class:" + targetClass, e);
        }
        return null;
    }

	/**
     * 把Bean数据转换到另外一个类的对象中，源对象的空值不转换。
     * 
     * @param source 数据源
     * @param target 目标对象
     */
	public static void copyProperties(Object source, Object target) throws BeansException {
		Class<?> actualEditable = target.getClass();
		PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
		for (PropertyDescriptor targetPd : targetPds) {
			if (targetPd.getWriteMethod() != null) {
				PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
				if (sourcePd != null && sourcePd.getReadMethod() != null) {
					try {
						Method readMethod = sourcePd.getReadMethod();
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(source);
						// 这里判断value是否为空（这里也能进行一些特殊要求的处理，例如绑定时格式转换等等。）
						if (value != null) {
							Method writeMethod = targetPd.getWriteMethod();
							if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
								writeMethod.setAccessible(true);
							}
							writeMethod.invoke(target, value);
						}
					} catch (Throwable ex) {
						throw new FatalBeanException( "Could not copy properties from source to target", ex);
					}
				}
			}
		}
	}

}
